use crate::config::API_BASE_URL;
use crate::entities::{ApiResponse, AuthResponse, LoginApiResponse, LoginRequest, RegisterRequest, User};
use reqwest::Client;
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static::lazy_static! {
    static ref USER_SESSIONS: Mutex<HashMap<String, User>> = Mutex::new(HashMap::new());
}

pub async fn login_user(credentials: LoginRequest) -> Result<AuthResponse, String> {
    let client = Client::new();
    
    let response = client
        .post(format!("{}/user/login", API_BASE_URL))
        .json(&credentials)
        .send()
        .await
        .map_err(|e| format!("网络请求失败: {}", e))?;

    let api_response: LoginApiResponse = response
        .json()
        .await
        .map_err(|e| format!("响应解析失败: {}", e))?;

    if api_response.status && api_response.code == 200 {
        let user_data = api_response.data.ok_or("用户数据缺失")?;
        let user: User = serde_json::from_value(user_data)
            .map_err(|e| format!("用户数据解析失败: {}", e))?;

        // 存储会话
        let token = user.token.clone();
        USER_SESSIONS.lock().unwrap().insert(token.clone(), user.clone());

        Ok(AuthResponse {
            data: Some(user),
            msg: Some(api_response.msg),
            status: true,
            code: api_response.code,
        })
    } else {
        Ok(AuthResponse {
            data: None,
            msg: Some(api_response.msg),
            status: false,
            code: api_response.code,
        })
    }
}

pub async fn register_user(user_info: RegisterRequest) -> Result<AuthResponse, String> {
    let client = Client::new();
    
    let response = client
        .post(format!("{}/user/register", API_BASE_URL))
        .json(&user_info)
        .send()
        .await
        .map_err(|e| format!("网络请求失败: {}", e))?;

    let api_response: ApiResponse<User> = response
        .json()
        .await
        .map_err(|e| format!("响应解析失败: {}", e))?;

    if api_response.status == 1 && api_response.code == 200 {
        Ok(AuthResponse {
            data: None,
            msg: Some(api_response.msg),
            status: true,
            code: api_response.code,
        })
    } else {
        Ok(AuthResponse {
            data: None,
            msg: Some(api_response.msg),
            status: false,
            code: api_response.code,
        })
    }
}

pub fn get_current_user(token: String) -> Result<Option<User>, String> {
    let sessions = USER_SESSIONS.lock().unwrap();
    Ok(sessions.get(&token).cloned())
}

pub fn logout_user(token: String) -> Result<bool, String> {
    let mut sessions = USER_SESSIONS.lock().unwrap();
    sessions.remove(&token);
    Ok(true)
}

pub fn get_current_jwt_token() -> Result<String, String> {
    let sessions = USER_SESSIONS.lock().unwrap();
    sessions.keys().next()
        .map(|token| token.to_string())
        .ok_or("未找到登录会话，请先登录".to_string())
}

pub fn check_login_status() -> Result<bool, String> {
    let sessions = USER_SESSIONS.lock().unwrap();
    Ok(!sessions.is_empty())
}

pub fn get_current_user_from_session() -> Result<Option<User>, String> {
    let sessions = USER_SESSIONS.lock().unwrap();
    Ok(sessions.values().next().cloned())
}